package com.zxq.tcp.util;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import java.util.ArrayList;
import java.util.List;

public class TranscodeUtils {


    /**
     * 帧头
     */
    static final byte headFlag = 0x7E;

    /**
     * 帧尾
     */
    static final byte tailFlag = 0x7F;

    /**
     * 转码标志
     */
    static final byte markFlag = 0x7D;

    /**
     * 异或字节
     */
    static final byte xorFlag = 0x20;

    /**
     * 解码的时候转码操作
     * @param src 源数据
     * @return
     */
    public static byte[] transcodeDecoder(byte[] src) {
        List<Byte> reverseList = new ArrayList<>();

        boolean mark = false;
        for (byte b : src) {
            if (mark) {
                byte reverseByte = (byte) (b ^ xorFlag);
                reverseList.add(reverseByte);
                mark = false;
            } else if (b == markFlag) {
                mark = true;
                continue;
            } else {
                reverseList.add(b);
            }
        }

        int buffLen = reverseList.size();
        byte[] buff = new byte[buffLen];

        for (int i = 0; i < buffLen; i++) {
            buff[i] = reverseList.get(i);
        }

        return buff;
    }


    /**
     * 编码的时候转码操作
     * @param data 数据
     * @return
     */
    private static byte[] transCodeEncoder(byte[] data) {

        List<Byte> byteList= new ArrayList<>();
        for(byte b : data) {
            boolean isMark = (b == headFlag) || (b == tailFlag) || (b == markFlag);
            if(isMark) {
                byteList.add(markFlag);
                byteList.add((byte) (b ^ xorFlag));
            } else {
                byteList.add(b);
            }
        }

        byte[] bytes=new byte[byteList.size()];
        for(int i=0;i<bytes.length;i++) {
            bytes[i]=byteList.get(i);
        }

        return bytes;
    }



    public static void main(String[] args) {
        String src = "7E7F7D";
        System.out.println("src: " + src);
        byte[] srcBuff = transCodeEncoder(HexBin.decode(src));
        System.out.println("transcode encoder: " + HexBin.encode(srcBuff));
        byte[] decodeBuff = transcodeDecoder(srcBuff);
        System.out.println("transcode decoder: " + HexBin.encode(decodeBuff));
    }




}
